﻿using System.Web.Mvc;
using PCE.Core;
using PCE.Data;
using PCE.Data.Queries;
using PCE.Domain;
using PCE.Mvc.Filters;
using PCE.Mvc.Model;
using Microsoft.Web.Mvc;

namespace PCE.Mvc.Controllers
{
	public class LoginController : Controller
	{
		private readonly IAuthenticator _authenticator;

		private readonly IRepository<Customer, int> _customerRepository;

		public LoginController(IAuthenticator authenticator, IRepository<Customer, int> customerRepository)
		{
			_authenticator = authenticator;

			_customerRepository = customerRepository;
		}

		[HttpGet]
		public ActionResult LogOn()
		{
			return View();
		}

		[HttpPost]
		[PersistanceRequired]
		public ActionResult LogOn(LoginDetails details)
		{
			if (!ModelState.IsValid)
				return View();

			var customer = _customerRepository.Find(CustomerSpecs.WithAuthentication(details.Login, details.Password));

			if (customer != null)
			{
				_authenticator.SignIn(customer.Id);
				return RedirectToAction("Edit", "Profile");
			}
			
			ModelState.AddModelError(string.Empty, "Пользователь не существует");
			
			return View();
		}

		[HttpGet]
		public ActionResult LogOut()
		{
			_authenticator.SignOut();

			return this.RedirectToAction<HomeController>(c => c.Index());
		}
	}
}